package org.confucianismframework.orm;

import lombok.SneakyThrows;
import org.confucianismframework.orm.enums.SQLType;
import org.confucianismframework.orm.sql.produce.SqlProduce;
import org.confucianismframework.orm.sql.produce.SqlProduceFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Types;
import java.util.List;

/**
 * SpringJdbcTemplate 二次开发
 *
 * @author zy
 */
@Component
public class FastJdbcTemplate extends JdbcTemplate {

    public FastJdbcTemplate() {}

    /* ===================== 支持数据源引入 ===================== */

    public FastJdbcTemplate(DataSource dataSource) {
        super(dataSource);
    }

    public FastJdbcTemplate(DataSource dataSource, boolean lazyInit) {
        super(dataSource, lazyInit);
    }

    /* ===================== CRUD ===================== */

    /**
     * 查询全部
     * @param entity
     * @param <T>
     * @return
     */
    public <T> List<T> selectAll(T entity) {
        SqlProduce sqlProduce = SqlProduceFactory.instance().build(SQLType.SELECT);
        String sql = sqlProduce.produce(entity);
        RowMapper<T> rowMapper = new BeanPropertyRowMapper<>();
        return super.query(sql, rowMapper);
    }



    /**
     * 添加
     * @param entity
     * @param <T>
     * @return
     */
    public <T> int save(T entity) {
        return processUpdate(entity, SQLType.INSERT);
    }

    /**
     * 修改
     * @param entity
     * @param <T>
     * @return
     */
    public <T> int update(T entity) {
        return processUpdate(entity, SQLType.UPDATE);
    }

    /**
     * 根据对象删除
     * @param entity
     * @param <T>
     * @return
     */
    public <T> int delete(T entity) {
        return processUpdate(entity, SQLType.DELETE);
    }

    /**
     * 根据 id 删除
     * @param entity
     * @param id
     * @param <T>
     * @return
     */
    public <T> int delete(T entity, Serializable id) {
        SqlProduce sqlProduce = SqlProduceFactory.instance().build(SQLType.DELETE);
        String sql = sqlProduce.produce(entity);
        return update(sql, id);
    }


    /**
     * 增删改前置设置
     * @param entity
     * @param sqlType
     * @param <T>
     * @return
     */
    private <T> int processUpdate(T entity, SQLType sqlType) {
        String sql = null;
        Object[] args = null;
        int[] argTypes = null;
        try {

            SqlProduce sqlProduce = SqlProduceFactory.instance().build(sqlType);
            sql = sqlProduce.produce(entity);

            args = this.setArgs(entity, sqlType);

            argTypes = this.setArgTypes(entity, sqlType);

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return super.update(sql, args, argTypes);

    }

    /* ================ spring jdbcTemplate 所需参数 ================= */

    /**
     * 设置参数
     */
    @SneakyThrows
    private <T> Object[] setArgs(T entity, SQLType sqlType) throws IllegalAccessException {

        String sqlFlag = sqlType.getValue();

        Class<?> entityClass = entity.getClass();

        Field[] fields = entityClass.getDeclaredFields();

        Object[] args = null;

        if (sqlFlag.equals(SQLType.INSERT.getValue())) {

            args = getArgs(fields, entity);

        } else if (sqlFlag.equals(SQLType.UPDATE.getValue())) {

            Object[] tempArr = getArgs(fields, entity);

            args = new Object[fields.length];
            // 数组拷贝
            System.arraycopy(tempArr, 1, args, 0, tempArr.length - 1);

            args[args.length - 1] = tempArr[0];

        } else if (sqlFlag.equals(SQLType.DELETE.getValue())) {

            // 一个参数
            args = new Object[1];

            fields[0].setAccessible(true);

            args[0] = fields[0].get(entity);
        }

        return args;

    }

    /**
     * 设置参数类型
     */
    @SneakyThrows
    private <T> int[] setArgTypes(T entity, SQLType sqlType) throws IllegalAccessException {

        String sqlFlag = sqlType.getValue();

        Class<?> entityClass = entity.getClass();

        Field[] fields = entityClass.getDeclaredFields();

        int[] argTypes = null;

        if (sqlFlag.equals(SQLType.INSERT.getValue())) {

            argTypes = getArgTypes(fields, entity);

        } else if (sqlFlag.equals(SQLType.UPDATE.getValue())) {

            int[] tempArgTypes = getArgTypes(fields, entity);

            argTypes = new int[fields.length];

            // 数组拷贝
            System.arraycopy(tempArgTypes, 1, argTypes, 0, tempArgTypes.length - 1);

            argTypes[argTypes.length - 1] = tempArgTypes[0];


        } else if (sqlFlag.equals(SQLType.DELETE.getValue())) {

            argTypes = new int[1];

            fields[0].setAccessible(true);

            if (fields[0].get(entity).getClass().getName().equals("java.lang.String")) {
                argTypes[0] = Types.VARCHAR;
            } else if (fields[0].get(entity).getClass().getName().equals("java.lang.Integer")) {
                argTypes[0] = Types.INTEGER;
            }
        }
        return argTypes;
    }

    /**
     * 获取参数类型 ( 重复代码封装 )
     */
    @SneakyThrows
    private <T> int[] getArgTypes(Field[] fields, T entity) throws IllegalAccessException {
        int[] argTypes = new int[fields.length];
        for (int i = 0; i < argTypes.length; i++) {
            fields[i].setAccessible(true);
            if (fields[i].get(entity).getClass().getName().equals("java.lang.String")) {
                argTypes[i] = Types.VARCHAR;
            } else if (fields[i].get(entity).getClass().getName().equals("java.lang.Double")) {
                argTypes[i] = Types.DECIMAL;
            } else if (fields[i].get(entity).getClass().getName().equals("java.lang.Integer")) {
                argTypes[i] = Types.INTEGER;
            } else if (fields[i].get(entity).getClass().getName().equals("java.util.Date")) {
                argTypes[i] = Types.DATE;
            }
        }
        return argTypes;
    }



    /**
     * 获取参数 ( 重复代码封装 )
     */
    @SneakyThrows
    private <T> Object[] getArgs(Field[] fields, T entity) throws IllegalAccessException {
        Object[] args = new Object[fields.length];
        for (int i = 0; i < args.length; i++) {
            fields[i].setAccessible(true);
            args[i] = fields[i].get(entity);
        }
        return args;
    }


}
